package com.bw.gmall.realtime.app.dwd.xz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * 提取商品详情页浏览明细
 */
public class DwdTrafficItemDetailView {
    public static void main(String[] args) throws Exception {
        // 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 2. 读取页面日志主题
        String topic = "dwd_traffic_page_log";
        String groupId = "dwd_traffic_item_detail_view";
        SingleOutputStreamOperator<JSONObject> pageLogDS = env
                .addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId))
                .flatMap(new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        try {
                            out.collect(JSON.parseObject(value));
                        } catch (Exception e) {
                            System.out.println("脏数据: " + value);
                        }
                    }
                });

        // 3. 过滤商品详情页数据（复用BaseLogApp的过滤逻辑）
        SingleOutputStreamOperator<JSONObject> itemDetailDS = pageLogDS.process(
                new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject jsonObj, Context ctx, Collector<JSONObject> out) {
                        String pageId = jsonObj.getJSONObject("page").getString("page_id");
                        if ("good_detail".equals(pageId)) {
                            // 保留商品ID等核心字段
                            JSONObject result = new JSONObject();
                            result.put("common", jsonObj.getJSONObject("common"));
                            result.put("page", jsonObj.getJSONObject("page"));
                            result.put("ts", jsonObj.getLong("ts"));
                            out.collect(result);
                        }
                    }
                }
        );

        // 4. 写入商品详情页浏览主题
        String targetTopic = "dwd_traffic_item_detail_view";
        itemDetailDS.print(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        itemDetailDS.map(jsonObj -> jsonObj.toJSONString())
                .addSink(MyKafkaUtil.getFlinkKafkaProducer(targetTopic));

        env.execute("DwdTrafficItemDetailView");
    }
}
